// 提取token
const { token } = JSON.parse(sessionStorage.getItem('tokenData'));

// 请求数据
const reqDataByGet = function(token, fn) {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();
		xhr.open('GET', `https://api.dsstudio.tech/wx/?token=${token}&fn=${fn}`);
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4 && xhr.status == 200) {
				console.log('请求的数据是')
				console.log(xhr.response)
				resolve(xhr.response);
			}
		}
		xhr.send(null);
	})
	.then(res => {
		// console.log(JSON.parse(JSON.parse(res).result.resp_data))
		let resp_data = JSON.parse(JSON.parse(res).result.resp_data);
		return resp_data;
	})
}
const reqDataByPost = function(token, fn, queryStr) {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();
		xhr.open('POST', 'https://api.dsstudio.tech/wx/');
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4 && xhr.status == 200) {
				resolve(xhr.response);
			}
		}
		xhr.send(`token=${token}&fn=${fn}&${queryStr}`);
	})
	.then(res => {
		let { result } = JSON.parse(res);
		if(result.errcode === 0) {
			// console.log(JSON.parse(JSON.parse(res).result.resp_data))
			let resp_data = JSON.parse(JSON.parse(res).result.resp_data);
			console.log(resp_data)
			return resp_data;
		}
	})
}

// 转换日期格式
const transDate = function(date) {
	if(date.indexOf('-') + 1) {  // 此时日期是yyyy-mm-dd格式
		let dateArr = date.split('-');
		for(let i = 1; i < dateArr.length; i++) {
			if(dateArr[i][0] == '0') dateArr[i] = dateArr[i].slice(1);
		}
		return dateArr.join('/');
	} else {  // 此时日期是yyyy/mm/dd格式
		let dateArr = date.split('/');
		dateArr[1] = ('0' + dateArr[1]).slice(-2);
		dateArr[2] = ('0' + dateArr[2]).slice(-2);
		return dateArr.join('-');
	}
}
// const reqDataByPost = function(formEl, token, fn) {
// 	return new Promise((resolve, reject) => {
// 		let form = document.querySelector(formEl);
// 		let formData = new FormData(form);
// 		formData.set('token', token);
// 		formData.set('fn', fn);
		
// 		const xhr = new XMLHttpRequest();
// 		xhr.open('POST', 'https://api.dsstudio.tech/wx/');
// 		xhr.onreadystatechange = function() {
// 			if(xhr.readyState == 4 && xhr.status == 200) {
// 				resolve(xhr.response);
// 			}
// 		}
// 		xhr.send(formData);
// 	})
// }

const articles = {
	template: '#articles',
	data() {
		return {
			tableData: [],
			isMod: false,  // 当前模态框是需要进行添加操作还是修改操作，从而切换提交按钮的行为
			newArti: {  // 添加文章时的表单数据
				title: '',
				lastRevisionTime: '',
				body: ''
			},
			artiId: ''  // 记录当前操作的文章的id
		}
	},
	beforeMount() {
		reqDataByGet(token, 'listArticles')
		.then(resp_data => {
			console.log(resp_data)
			resp_data.result.data.forEach(item => {
				this.tableData.push({
					id: item._id,
					lastRevisionTime: new Date(item.lastRevisionTime).toLocaleDateString(),
					title: item.content.title,
					body: item.content.body
				})
			})
			// this.tableData = resp_data.result.data;
			console.log(this)
		})
		.catch(reason => {
			console.log(reason);
		})
	},
	methods: {
		toFillArtiInfo(row) {
			console.log(row)
			this.isMod = true;   // 修改提交按钮的默认（添加）行为
			this.artiId = row.id;
			this.newArti.title			   = row.title;
			this.newArti.lastRevisionTime  = transDate(row.lastRevisionTime);
			this.newArti.body			   = row.body;
		},
		addOrModArti() {
			// 组装数据
			let content = {
				lastRevisionTime: new Date(this.newArti.lastRevisionTime).getTime(),
				content: {
					title: this.newArti.title,
					body: this.newArti.body
				}
			}
			content = JSON.stringify(content);
			
			if(this.isMod) {  // 修改功能
				console.log('修改功能')
				reqDataByPost(token, 'modifyArticle', `id=${this.artiId}&content=${content}`)
				.then(data => {
					console.log(data)
					if(data.code === 0) {  // 修改成功后前端重新渲染该条目的数据
						this.tableData.forEach(item => {
							if(item.id === this.artiId) {
								// let tmpDate = this.newArti.lastRevisionTime.split('-');
								item.title = this.newArti.title;
								item.lastRevisionTime = transDate(this.newArti.lastRevisionTime);
								item.body = this.newArti.body;
							}
						})
					}
				})
				.catch(reason => {
					console.log(reason);
				})
				this.isMod = false;   // 恢复提交按钮的默认行为
			} else {     // 添加功能
				console.log('添加功能')
				// 发送数据
				reqDataByPost(token, 'addArticle', `content=${content}`)
				.then(data => {
					let content = JSON.parse(data.result.content);
					console.log('content')
					console.log(content)
					let newArti = {
						lastRevisionTime: new Date(content.lastRevisionTime).toLocaleDateString(),
						title: content.content.title,
						body: content.content.body
					};
					this.tableData.push(newArti);
				})
				.catch(reason => {
					console.log(reason);
				})
			}
		},
		toDelArti(row) {
			reqDataByPost(token, 'deleteArticle', `id=${row.id}`)
			.then(res => {
				console.log(res)
				if(res.code === 0) {
					console.log('删除成功'+row.id)
					this.tableData.forEach((item, index) => {
						if(item.id === row.id) {
							this.tableData.splice(index, 1);
						}
					})
				}
			})
			.catch(reason => {
				console.log(reason);
			})
		}
	}
}

const cards = {
	template: '#cards',
	data() {
		return {
			selDate: '',
			hasAppendix: true,
			tableData: []
		}
	},
	beforeMount() {
		reqDataByGet(token, 'listCards')
		.then(resp_data => {
			console.log('卡片列表')
			console.log(resp_data)
			this.tableData = resp_data.result.data;
			// console.log(JSON.parse(JSON.parse(res).result.resp_data))
		})
		.catch(reason => {
			console.log(reason);
		})
	},
	filters: {
		isTrue(val) {
			if(val) {
				return '是';
			} else {
				return '否';
			}
		}
	}
}

const books = {
	template: '#books',
	data() {
		return {
			tableData: [],
			isMod: false,  // 当前模态框是需要进行添加操作还是修改操作，从而切换提交按钮的行为
			addBook: {
				title: '',
				author: '',
				publishTime: '',
				publisher: '',
				introduction: '',
				isbn: '',
				cover: '',
				location: [],
				filePath: ''
			},
			bookId: ''  // 记录当前操作的书籍的id
		}
	},
	beforeMount() {
		reqDataByGet(token, 'listBooks')
		.then(resp_data => {
			console.log('书籍列表')
			console.log(resp_data)
			
			let {data} = resp_data.result;
			console.log(data)
			data.forEach(item => {
				this.tableData.push(this.parseBookData(item))
			})
		})
		.catch(reason => {
			console.log(reason);
		})
	},
	methods: {
		getFilePath(e) {
			console.log(e)
			this.addBook.filePath = e.target.value;
		},
		addOrModBook() {
			console.log('toAddBook')
			// 上传图片
			new Promise((resolve, reject) => {
				let formdata = new FormData();
				let file_obj = document.querySelector('input#cover[type=file]').files[0];
				formdata.set('cover', file_obj);
				
				let xhr = new XMLHttpRequest();
				xhr.open('POST', 'https://api.dsstudio.tech/wx/upload');
				xhr.onreadystatechange = function() {
					if(xhr.readyState == 4 && (xhr.status >= 200 || xhr.status < 300)) {
						resolve(xhr.response);
					}
				}
				xhr.send(formdata);
			})
			.then(res => {
				console.log('上传文件成功')
				res = JSON.parse(res);
				if(res.code === 0) {
					return res.result;
				}
			})
			.then(cover_url => {
				console.log(cover_url)
				// 上传图片成功返回图片url，将url组装进json
				// 组装数据
				let content = {
					title:		  this.addBook.title,
					author: 	  this.addBook.author.split('、'),
					publishTime:  new Date(this.addBook.publishTime).getTime(),
					publisher:    this.addBook.publisher,
					introduction: this.addBook.introduction,
					isbn:		  this.addBook.isbn,
					cover:		  cover_url,
					location:	  []
				}
				content = JSON.stringify(content);
				// 发送数据
				reqDataByPost(token, 'addBook', `content=${content}`)
				.then(data => {
					console.log('添加数据结果：')
					if(data.code == 0) {
						this.tableData.push(this.parseBookData(data.result))
					}
				})
				.catch(reason => {
					console.log(reason);
				})
			})
			.catch();
		},
		toDelBook(row) {
			console.log('删除书籍')
			reqDataByPost(token, 'removeBook', `id=${row.id}`)
			.then(res => {
				if(res.code === 0) {
					console.log('删除成功'+row.id)
					this.tableData.forEach((item, index) => {
						if(item.id === row.id) {
							this.tableData.splice(index, 1);
						}
					})
				}
			})
			.catch(reason => {
				console.log(reason);
			})
		},
		// 解析书籍数据（比如将时间戳转换成年月日、拆分数组数据等）
		parseBookData(data) {
			return {
				id: 		  data._id,
				title:		  data.title,
				author: 	  data.author.join('、'),
				cover:		  data.cover,
				introduction: data.introduction,
				isbn:		  data.isbn,
				location:	  data['location'].join('、'),
				publishTime:  new Date(data.publishTime).toLocaleDateString(),
				publisher:	  data.publisher
			}
		}
	}
}

const users = {
	template: '#users',
	data() {
		return {
			tableData: [],
			newUser: {
				openid: '',
				maxBorrowingCount: 0,
				credit: 0,
				name: '',
				location: '',
				contact: ''
			},
			userId: ''  // 记录当时需要修改信息的用户的id
		}
	},
	beforeMount() {
		reqDataByGet(token, 'listUsers')
		.then(resp_data => {
			console.log('用户列表')
			console.log(resp_data)
			this.tableData = resp_data.result.data;
			// console.log(JSON.parse(JSON.parse(res).result.resp_data))
		})
		.catch(reason => {
			console.log(reason);
		})
	},
	methods: {
		toFillUserInfo(row) {
			console.log(row)
			this.userId					   = row._id;
			this.newUser.openid			   = row._openid;
			this.newUser.maxBorrowingCount = row.maxBorrowCount;
			this.newUser.credit			   = row.credit;
			this.newUser.name			   = row.name;
			this.newUser.location		   = row.location;
			this.newUser.contact		   = row.contact;
		},
		toUpdateUser() {
			let content = JSON.stringify(this.newUser);
			// 发送数据
			reqDataByPost(token, 'updateUser', `id=${this.userId}&content=${content}`)
			.then(data => {
				console.log('添加用户结果：')
				if(data.code === 0) {
					// this.tableData.push(this.newUser);
					console.log(data)
				}
				// this.tableData = resp_data.result.data;
			})
			.catch(reason => {
				console.log(reason);
			})
		}
	}
}

const circulate = {
	template: '#circulate',
	data() {
		return {
			isOpen: true,
			tableData: []
		}
	},
	beforeMount() {
		reqDataByGet(token, 'listRecords')
		.then(resp_data => {
			console.log('借还书列表')
			console.log(resp_data)
			this.tableData = resp_data.result.data;
			// console.log(JSON.parse(JSON.parse(res).result.resp_data))
		})
		.catch(reason => {
			console.log(reason);
		})
	}
}

const router = new VueRouter({
	routes: [
		{
			path: '/',
			redirect: 'articles'
		},
		{
			path: '/articles',
			component: articles,
		},
		{
			path: '/cards',
			component: cards,
		},
		{
			path: '/books',
			component: books
		},
		{
			path: '/users',
			component: users
		},
		{
			path: '/circulate',
			component: circulate
		}
	]
})

const vm = new Vue({
	el: '#all-box',
	data: {
		selDate: '',
		tokenData: ''
	},
	beforeCreate() {
		// console.log(token)
		// console.log(createTime)
		if(!sessionStorage.getItem('tokenData')) {
			window.location.href = './login.html';
		} else {
			var { token, createTime } = JSON.parse(sessionStorage.getItem('tokenData'));
		}
		
		if(new Date().getTime() - createTime > 15*60*1000) {
			window.location.href = './login.html';
		} else {
			this.tokenData = JSON.parse(sessionStorage.getItem('tokenData'));
		}
	},
	methods: {
		
	},
	router
})